﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Organizations;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bop;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.Materials.Dto;
using Camc.Quality.OperationHistory;
using Camc.Quality.Quality;
using Camc.Quality.RecordTable.FormClass;
using Camc.Quality.StoreManagement.SoreModel.Dto;
using Camc.Quality.StoreManagement.StoraePut;
using Camc.Quality.StoreManagement.StoragePut;
using Camc.Quality.StoreManagement.StoragePut.Dto;
using Camc.Quality.SystemManagement;
using Camc.Quality.TrepanningManager.BomAnalyse;
using Camc.Quality.TrepanningManager.MatingManager;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Camc.Quality.StoreManagement.StoreEnum;

namespace Camc.Quality.StoreManagement.StoreInfo
{
    public class StoreInfoAppService : QualityAppServiceBase
    {
        private readonly IRepository<StoreStock, Guid> _storeStockRepository;
        private readonly IRepository<StoreStockContent, Guid> _storeStockContentRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<StorePutContent, Guid> _storePutContentRepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IAbpSession _abpSession;
        private readonly StorePutAppService _storePutAppServiceRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        private readonly MaterialsAppService _materialsAppServiceRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IRepository<StorePutRecord, Guid> _storePutRecordRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<LoadPieceEntity, Guid> _loadPieceEntityRepository;
        private readonly IRepository<WorkStepEntity, Guid> _workStepEntityRepository;
        private readonly IRepository<ProcessesEntity, Guid> _processesEntityRepository;
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<TechniqueEntity, Guid> _techniqueEntityRepository;
        private readonly BomAnalyseAppService _bomAnalyseAppServiceRepository;
        private readonly MatingManagerAppService _matingManagerAppServiceRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly CodeFormatDescAppService _codeFormatDescAppServiceRepository;

        public StoreInfoAppService(IRepository<StoreStock, Guid> storeStockRepository,
                                  IRepository<StoreStockContent, Guid> storeStockContentRepository,
                                  IRepository<User, long> userRepository,
                                  IRepository<StorePutContent, Guid> storePutContentRepository,
                                  IRepository<MaterialsContent, Guid> materialsContentRepository,
                                  IRepository<MaterialsNode, Guid> materialsNodeRepository,
                                  IAbpSession abpSession,
                                  StorePutAppService storePutAppServiceRepository,
                                  IRepository<OrganizationUnit, long> organizationUnitRepository,
                                  IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
                                  MaterialsAppService materialsAppServiceRepository,
                                  IOperationHistoryAppService iOperationHistoryAppService,
                                  IRepository<StorePutRecord, Guid> storePutRecordRepository,
                                  IRepository<Sys_Code, Guid> sysCodeRepository,
                                  IRepository<LoadPieceEntity, Guid> loadPieceEntityRepository,
                                  IRepository<WorkStepEntity, Guid> workStepEntityRepository,
                                  IRepository<ProcessesEntity, Guid> processesEntityRepository,
                                  IRepository<BopNode, Guid> bopNodeRepository,
                                  IRepository<TechniqueEntity, Guid> techniqueEntityRepository,
                                  BomAnalyseAppService bomAnalyseAppServiceRepository,
                                  MatingManagerAppService matingManagerAppServiceRepository,
                                  IUnitOfWorkManager unitOfWorkManager,
                                  CodeFormatDescAppService codeFormatDescAppServiceRepository
            )
        {
            _storeStockRepository = storeStockRepository;
            _storeStockContentRepository = storeStockContentRepository;
            _userRepository = userRepository;
            _storePutContentRepository = storePutContentRepository;
            _materialsContentRepository = materialsContentRepository;
            _materialsNodeRepository = materialsNodeRepository;
            _abpSession = abpSession;
            _storePutAppServiceRepository = storePutAppServiceRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;
            _materialsAppServiceRepository = materialsAppServiceRepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _storePutRecordRepository = storePutRecordRepository;
            _sysCodeRepository = sysCodeRepository;
            _loadPieceEntityRepository = loadPieceEntityRepository;
            _workStepEntityRepository = workStepEntityRepository;
            _processesEntityRepository = processesEntityRepository;
            _bopNodeRepository = bopNodeRepository;
            _techniqueEntityRepository = techniqueEntityRepository;
            _bomAnalyseAppServiceRepository = bomAnalyseAppServiceRepository;
            _matingManagerAppServiceRepository = matingManagerAppServiceRepository;
            _unitOfWorkManager = unitOfWorkManager;
            _codeFormatDescAppServiceRepository = codeFormatDescAppServiceRepository;
        }
        /// <summary>
        /// 库存信息查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<StoreInfoDto>> GetStoreInfoList(GetStoreInfoListInput input)
        {
            var userTemp = _userRepository.GetAll().ToList();
            var materialsNode = _materialsNodeRepository.GetAll();
            var storeStockList = from spc in _storePutContentRepository.GetAll()
                                 join mc in _materialsContentRepository.GetAll()
                                 on spc.MaterialsContentId equals mc.Id
                                 where spc.StoreStateContent == StoreState.已入库
                                 select new StoreInfoDto
                                 {
                                     #region 仓库信息 
                                     Id = spc.Id,
                                     //入库单号
                                     StorePutNo = spc.StorePutNo,
                                     // 物料细料ID
                                     MaterialsContentId = spc.MaterialsContentId,
                                     // 仓库ID
                                     StoreId = spc.StoreId,
                                     // 仓库名称
                                     StroeName = spc.StroeName,
                                     // 储位ID
                                     BinLocationId = spc.BinLocationId,
                                     // 储位
                                     BinLocation = spc.BinLocation,
                                     // 放行单号
                                     ReleaseOrder = spc.ReleaseOrder,
                                     //备注
                                     Remark = spc.Remark,
                                     // 入库时间
                                     StorePutTime = spc.StorePutTime,
                                     // 入库人
                                     StorePutPeople = userTemp.FirstOrDefault(d => d.Id == spc.CreatorUserId).Surname + userTemp.FirstOrDefault(d => d.Id == spc.CreatorUserId).Name,
                                     //入库方式
                                     WarehousMethod = (int)spc.WarehousMethod,
                                     //物料入库状态 0待入库、1已入库
                                     StoreStateContent = (int)spc.StoreStateContent,
                                     // 确认人ID
                                     IdentifyingPeopleId = spc.IdentifyingPeopleId,
                                     // 确认人
                                     IdentifyingPeople = userTemp.FirstOrDefault(d => d.Id == spc.IdentifyingPeopleId).Surname + userTemp.FirstOrDefault(d => d.Id == spc.IdentifyingPeopleId).Name,
                                     // 确认时间
                                     IdentifyingTime = spc.IdentifyingTime,
                                     #endregion

                                     #region 合格证信息 
                                     // 合格证号
                                     QualifiedNumber = spc.QualifiedNumber,
                                     // 产品图号
                                     ProductDrawingNo = spc.ProductDrawingNo,
                                     // 产品名称
                                     ProductName = spc.ProductName,
                                     //产品编号(件号)
                                     ProductNumber = spc.ProductNumber,
                                     ProductNumberShow = spc.ProductNumberShow,
                                     // 批次
                                     Batch = spc.Batch,
                                     // 合格证号任务
                                     QualifiedTaskNumber = spc.QualifiedTaskNumber,
                                     // 特殊记载
                                     SpecialRecords = spc.SpecialRecords,
                                     // 金属材料牌号状态
                                     MaterialBrandStatus = spc.SpecialRecords,
                                     // 炉(批)号
                                     HeatNumber = spc.HeatNumber,
                                     // 化(试)验号
                                     Mthd = spc.Mthd,
                                     // 非金属材料牌号
                                     NonmetallicMaterialsBrand = spc.NonmetallicMaterialsBrand,
                                     // 批次号
                                     BatchNo = spc.BatchNo,
                                     // 压制日期
                                     SuppressionDate = spc.SuppressionDate,
                                     // 处理技术问题文件编号
                                     DocumentNo = spc.DocumentNo,
                                     // 制造车间
                                     ManufacturingWorkshop = spc.ManufacturingWorkshop,
                                     // 生产工人
                                     ProductionWorkers = spc.ProductionWorkers,
                                     // 工(组)长
                                     Foreman = spc.Foreman,
                                     // 检验员
                                     Inspector = spc.Inspector,
                                     // 日期
                                     Date = spc.Date,
                                     // 质控卡号
                                     QCCardNo = spc.QCCardNo,
                                     // 装配任务号
                                     AssemblyTaskNumber = spc.AssemblyTaskNumber,
                                     // 阶段标记
                                     StageMark = spc.StageMark,
                                     // 材料牌号
                                     MaterialGrade = spc.MaterialGrade,
                                     // 材料状态
                                     MaterialStatus = spc.MaterialStatus,
                                     // 材料规格
                                     MaterialSpecification = spc.Module,
                                     // 标准件规格
                                     StandardSpecification = spc.Module,
                                     // 技术条件
                                     TechnicalConditions = spc.TechnicalConditions,
                                     // 材料合格证
                                     MaterialCertificate = spc.MaterialCertificate,
                                     // 协作合格证
                                     CooperationCertificate = spc.CooperationCertificate,
                                     // 供应单位
                                     SupplyCompany = spc.SupplyCompany,
                                     // 非金属制造日期
                                     NonMetallicManufacturingDate = spc.NonMetallicManufacturingDate,
                                     // 非金属压制日期
                                     NonMetallicPressingDate = spc.NonMetallicPressingDate,
                                     #endregion

                                     #region 基础信息 
                                     // 型号(产品代号)
                                     ProductCodeName = spc.ProductCode,
                                     ProductCode = spc.ProductCodeId,
                                     // 发次
                                     SendTimeName = spc.SendTime,
                                     SendTime = spc.SendTimeId,
                                     //物料细分类别
                                     MaterialCategoryId = mc.MaterialCategoryId,
                                     MaterialCategory = materialsNode.FirstOrDefault(s => s.Id == mc.MaterialCategoryId).MaterialTypeName,
                                     //物料类别(有问题)
                                     MaterialsNodeId = mc.MaterialsNodeId,
                                     MaterialsNode = materialsNode.FirstOrDefault(s => s.Id == mc.MaterialsNodeId).MaterialTypeName,
                                     // 规格
                                     Module = spc.Module,
                                     // 有效期止
                                     ExpirationDate = spc.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : spc.ExpirationDate,
                                     // 单位Id
                                     UnitId = spc.UnitId,
                                     // 单位
                                     Unit = spc.Unit,
                                     //转批次
                                     TurnBatch = spc.TurnBatch,
                                     // 物料属性
                                     MaterialsProperty = (int)spc.MaterialsProperty,
                                     // 装配任务号
                                     AssemblingTaskCode = spc.AssemblyTaskNumber,
                                     // 库存数量
                                     StoreQuality = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == spc.Id && s.OutboundState != StoreStockContent.OutboundStates.出库).Count(),
                                     // 自由库存数量
                                     FreeStoreQuality = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == spc.Id && s.IsPreSuit == StoreStockContent.IsSuits.否 && s.IsSuit == StoreStockContent.IsSuits.否 && s.OutboundState != StoreStockContent.OutboundStates.出库 && (s.MaterialsProperty == MaterialsPropertys.正常品 || s.MaterialsProperty == MaterialsPropertys.返修正常品)).Count(),
                                     // 可用预配套数量
                                     UsableQuantityStock = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == spc.Id && s.IsPreSuit == StoreStockContent.IsSuits.是 && s.IsSuit == StoreStockContent.IsSuits.否).Count(),
                                     // 配套数量
                                     SuiteStock = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == spc.Id && s.IsSuit == StoreStockContent.IsSuits.是 && s.OutboundState != StoreStockContent.OutboundStates.出库).Count(),
                                     // 隔离单号
                                     IsolationCode = spc.IsolationCode,
                                     // 隔离原因
                                     IsolationReason = spc.IsolationReason,
                                     // 隔离人员
                                     IsolationUser = spc.IsolationUser,
                                     // 隔离时间
                                     IsolationTime = spc.IsolationTime,
                                     #endregion
                                     CreationTime = spc.CreationTime
                                 };
            storeStockList = storeStockList.WhereIf(input.StoreId != null, d => d.StoreId == input.StoreId)
                .WhereIf(!string.IsNullOrEmpty(input.ProductDrawingNo), d => d.ProductDrawingNo.Contains(input.ProductDrawingNo))
                .WhereIf(!string.IsNullOrEmpty(input.ProductName), d => d.ProductName.Contains(input.ProductName))
                .WhereIf(!string.IsNullOrEmpty(input.Module), d => d.Module == input.Module)
                .WhereIf(!string.IsNullOrEmpty(input.MaterialsNode), d => d.MaterialsNode == input.MaterialsNode)
                .WhereIf(!string.IsNullOrEmpty(input.MaterialCategory), d => d.MaterialCategory == input.MaterialCategory)
                .WhereIf(input.MaterialsProperty != null, d => d.MaterialsProperty == input.MaterialsProperty)
                .WhereIf(!string.IsNullOrEmpty(input.QualifiedNumber), d => d.QualifiedNumber == input.QualifiedNumber)
                .WhereIf(!string.IsNullOrEmpty(input.ReleaseOrder), d => d.ReleaseOrder == input.ReleaseOrder)
                .WhereIf(!string.IsNullOrEmpty(input.ProductCode), d => d.ProductCode == input.ProductCode)
                .WhereIf(!string.IsNullOrEmpty(input.SendTime), d => d.SendTime == input.SendTime);
            var count = storeStockList.Count();
            var query = storeStockList.OrderByDescending(e => e.CreationTime).PageBy(input).ToList();

            foreach (StoreInfoDto storeInfoDto in query)
            {
                var storeStockContent = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == storeInfoDto.Id);
                var result = ObjectMapper.Map<List<StoreStockContentDto>>(storeStockContent);
                storeInfoDto.StoreStockContentDto = result;
            }
            return new PagedResultDto<StoreInfoDto>(count, query);
        }
        /// <summary>
        /// 补录合格证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> SupplementaryCertificate(ReleaseOrderInputs input)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                var pn = string.Join(",", input.StorePutModelContentDto.Select(s => s.ProductNumber));
                if (pn != null && pn != "")
                {
                    StringBuilder errorMsg = new StringBuilder();
                    string msg = "";
                    string[] productNumber = (string.Join(",", input.StorePutModelContentDto.Select(s => s.ProductNumber))).Split(",");
                    string[] orderNumber = (string.Join("，", (input.ReleaseOrderDto.ProductNumber))).Split(",");
                    int StorePutQuantity = input.StorePutModelContentDto.Sum(x => x.Quantity);
                    if (StorePutQuantity != input.ReleaseOrderDto.Quantity)
                    {
                        result.code = 1;
                        result.Message = "合格证上的数量/产品编号(件号)和放行单上的不符";
                        return result;
                    }
                    //if (input.StorePutModelContentDto.ProductNumber.Length == productNumber.Length)
                    if (productNumber.Length == orderNumber.Length)
                    {
                        var productNumberList = productNumber.ToList();
                        var releaseOrderList = orderNumber.ToList();
                        //var storeInfoDtoList = input.StorePutModelContentDto.ProductNumber.ToList();
                        //var productNumberList = productNumber.ToList();

                        foreach (var item in releaseOrderList)
                        {
                            if (productNumberList.IndexOf(item) == -1)
                            {
                                result.code = 1;
                                result.Message = "合格证上的数量/产品编号(件号)和放行单上的不符";
                                return result;
                            }
                        }
                    }
                    else
                    {
                        result.code = 1;
                        result.Message = "合格证上的数量/产品编号(件号)和放行单上的不符";
                        return result;
                    }
                }
                var storePut = _storePutContentRepository.FirstOrDefaultAsync(s => s.Id == input.ReleaseOrderDto.Id).Result;
                //删除已存在的放行单号
                await _storePutContentRepository.DeleteAsync(input.ReleaseOrderDto.Id);
                //根据补录合格证重新生成合格证入库信息（可能存在多个合格证对一个放行单号的情况，所以删除已存在的放行单数据重新生成合格证入库信息）
                for (int i = 0; i < input.StorePutModelContentDto.Count(); i++)
                {
                    var query = input.StorePutModelContentDto.ToList();
                    List<string> sendTime = new List<string>(query[i].SendTime.Split(',').ToArray());
                    List<string> productCode = new List<string>(query[i].ProductCode.Split(',').ToArray());
                    #region 校验数据仓库中和物料信息中是否存在(根据图号、规格 判断物料详细表中是否存在，如果不存在就新增，否则仓库信息表中新增 状态为待入库)
                    //var queryStoreContent = _storePutContentRepository.FirstOrDefaultAsync(t => t.QualifiedNumber == query[i].QualifiedNumber && t.QualifiedNumber != null).Result;
                    var productDrawingNo = query[i].ProductDrawingNo;
                    var materialsNode = _materialsNodeRepository.FirstOrDefault(d => d.Id == query[i].MaterialsNodeId);
                    var year = "";
                    if (productDrawingNo.IndexOf("-") >= 0 && materialsNode.MaterialTypeName == "标准件")
                    {
                        productDrawingNo = query[i].ProductDrawingNo.Substring(0, query[i].ProductDrawingNo.LastIndexOf("-"));
                        year = query[i].ProductDrawingNo.Substring(query[i].ProductDrawingNo.LastIndexOf("-") + 1);
                    }
                    var queryMaterialsContents = _materialsContentRepository.FirstOrDefaultAsync(t => t.MaterialNo == productDrawingNo && t.Model == query[i].Module).Result;
                    if (queryMaterialsContents.IsUsed == 0)
                    {
                        result.code = 1;
                        result.Message = "该物料已经停用";
                        return result;
                    }
                    StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
                    if (queryMaterialsContents != null)
                    {
                        var nodeName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialsNodeId).MaterialTypeName;
                        var categoryName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialCategoryId).MaterialTypeName;
                        if (nodeName != query[i].MaterialsNode && categoryName != query[i].MaterialCategory)
                        {
                            result.code = 1;
                            result.Message = "物料分类、细类与物料详细信息不符";
                            return result;
                        }
                        storeReturnIdDto.MaterialsContentId = queryMaterialsContents.Id;
                    }
                    //查询物料建模，若没有对应的详细信息，就增加。
                    if (queryMaterialsContents == null)
                    {
                        storeReturnIdDto = await _storePutAppServiceRepository.CreateMaterialsContentByStore(query[i]);
                    }
                    #endregion
                    #region  添加仓库物料信息
                    if (query[i].WarehousMethod == 2 && query[i].NonMetallicPressingDate == null)
                    {
                        query[i].MaterialBrandStatus = query[i].MaterialGrade + "/" + query[i].MaterialStatus + "/" + query[i].MaterialSpecification;
                    }
                    if (query[i].WarehousMethod == 2 && query[i].NonMetallicPressingDate != null)
                    {
                        query[i].NonmetallicMaterialsBrand = query[i].MaterialGrade + "/" + query[i].MaterialStatus + "/" + query[i].MaterialSpecification;
                    }
                    var pnq = query[i].ProductNumber;
                    if (pnq == null || pnq == "")
                    {
                        pnq = storePut.ProductNumber;
                    }
                    var expirationDate = query[i].ExpirationDate ?? "2099-01-01T00:00:00.000Z";
                    StorePutContent storePutContent = new StorePutContent
                    {
                        #region 入库信息  
                        Id = Guid.NewGuid(),
                        //入库单号
                        StorePutNo = input.ReleaseOrderDto.StorePutNo,
                        //仓库Id
                        StoreId = input.ReleaseOrderDto.StoreId,
                        //仓库名称
                        StroeName = input.ReleaseOrderDto.StroeName,
                        BinLocationId = query[i].BinLocationId,
                        BinLocation = query[i].BinLocation,
                        //物料细料ID
                        MaterialsContentId = (Guid)storeReturnIdDto.MaterialsContentId,
                        //放行单号
                        ReleaseOrder = input.ReleaseOrderDto.ReleaseOrder,
                        //备注
                        Remark = query[i].Remark,
                        //物料入库状态 0待入库、1已入库
                        StoreStateContent = StoreState.已入库,
                        //入库人Id
                        StorePutPeopleId = input.ReleaseOrderDto.StorePutPeopleId,
                        //入库时间
                        StorePutTime = (DateTime)input.ReleaseOrderDto.StorePutTime,
                        // 确认人ID
                        IdentifyingPeopleId = input.ReleaseOrderDto.IdentifyingPeopleId,

                        IdentifyingTime = input.ReleaseOrderDto.IdentifyingTime,

                        #endregion
                        #region 合格证信息 
                        //合格证号
                        QualifiedNumber = query[i].QualifiedNumber,
                        //产品图号
                        ProductDrawingNo = query[i].ProductDrawingNo,
                        //产品名称
                        ProductName = query[i].ProductName,
                        //批次
                        Batch = query[i].Batch,
                        //合格证号任务
                        QualifiedTaskNumber = query[i].QualifiedTaskNumber,
                        //数量
                        Quantity = query[i].Quantity,
                        //产品编号(件号)
                        ProductNumber = pnq,
                        //产品编号生成方式 0：自动带出，1：手动输入， 3：自动生成
                        ProductNumberType = 0,
                        //特殊记载
                        SpecialRecords = query[i].SpecialRecords,
                        //金属材料牌号状态  
                        MaterialBrandStatus = query[i].MaterialBrandStatus,
                        //非金属材料牌号
                        NonmetallicMaterialsBrand = query[i].NonmetallicMaterialsBrand,
                        //炉(批)号
                        HeatNumber = query[i].HeatNumber,
                        //化(试)验号
                        Mthd = query[i].Mthd,
                        //批次号
                        BatchNo = query[i].BatchNo,
                        //压制日期
                        SuppressionDate = query[i].SuppressionDate,
                        //处理技术问题文件编号
                        DocumentNo = query[i].DocumentNo,
                        //制造车间
                        ManufacturingWorkshop = query[i].ManufacturingWorkshop,
                        //生产工人
                        ProductionWorkers = query[i].ProductionWorkers,
                        //工(组)长
                        Foreman = query[i].Foreman,
                        //检验员
                        Inspector = query[i].Inspector,
                        //日期
                        Date = query[i].Date,
                        //质控卡号
                        QCCardNo = query[i].QCCardNo,
                        //装配任务号
                        AssemblyTaskNumber = query[i].AssemblyTaskNumber,
                        //阶段标记
                        StageMark = query[i].StageMark,
                        //材料牌号
                        MaterialGrade = query[i].MaterialGrade,
                        //材料状态
                        MaterialStatus = query[i].MaterialStatus,
                        ////材料规格
                        //MaterialSpecification = query[i].MaterialSpecification,
                        ////标准件规格
                        //StandardSpecification = query[i].StandardSpecification,
                        //技术条件
                        TechnicalConditions = query[i].TechnicalConditions,
                        //材料合格证
                        MaterialCertificate = query[i].MaterialCertificate,
                        //协作合格证
                        CooperationCertificate = query[i].CooperationCertificate,
                        //供应单位
                        SupplyCompany = query[i].SupplyCompany,
                        //非金属制造日期
                        NonMetallicManufacturingDate = query[i].NonMetallicManufacturingDate,
                        //非金属压制日期
                        NonMetallicPressingDate = query[i].NonMetallicPressingDate,
                        #endregion
                        #region 基础信息  
                        //型号(产品代号)
                        ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description)),
                        ProductCodeId = query[i].ProductCode,
                        //发次
                        SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description)),
                        SendTimeId = query[i].SendTime,
                        //规格型号
                        Module = query[i].Module,
                        //有效期止
                        ExpirationDate = expirationDate,
                        //单位Id
                        UnitId = (Guid)query[i].UnitId,
                        //单位
                        Unit = query[i].Unit,
                        //转批次
                        TurnBatch = query[i].TurnBatch,
                        //物料属性
                        MaterialsProperty = MaterialsPropertys.正常品,
                        ////入库状态
                        //InputState = StorePutContent.InputStates.已入库,
                        //入库方式
                        WarehousMethod = 0,
                        // 库存量
                        Amount = query[i].Amount,
                        // 所有产品编码
                        JianNum = query[i].JianNum,
                        //接收车间
                        InceptWorkshop = query[i].InceptWorkshop

                        #endregion
                    };
                    var index = storePutContent.ProductCode.IndexOf("系列");
                    if (index > 0)
                    {
                        storePutContent.SendTime = "全发次";
                        var st = _sysCodeRepository.FirstOrDefault(s => s.Description == "全发次");
                        if (st != null)
                        {
                            storePutContent.SendTimeId = st.Id.ToString().ToUpper();
                        }
                    }
                    _iOperationHistoryAppService.InsertOperationLogNew(storePutContent.Id, BusinessTypes.仓库管理, OperationTypes.仓库修改物料, "补录合格证");
                    //_iOperationHistoryAppService.InsertOperationLog(storePutContent.Id, 6, 19, "补录合格证");
                    #endregion

                    #region 更新库存主表信息
                    //理论上已经放行单入库，库存信息主表里肯定会有该物料数据，也没有字段需要更新
                    var storeStock = _storeStockRepository.FirstOrDefaultAsync(s => s.MaterialsContentId == query[i].MaterialsContentId && s.StoreId == query[i].StoreId);
                    if (storeStock == null)
                    {
                        result.code = 1;
                        result.Message = "仓库里没有该物料信息，请确认该物料是否已放行单入库";
                        return result;
                    }
                    #endregion
                    #region 库存详细信息更新
                    if (query[i].ProductNumber != null && query[i].ProductNumber != "")
                    {
                        string[] productNumberArray = query[i].ProductNumber.Split(',');
                        for (int t = 0; t < query[i].Quantity; t++)
                        {
                            var storeStockContent = _storeStockContentRepository.FirstOrDefaultAsync(s => s.StorePutContentId == input.ReleaseOrderDto.Id && s.ProductNumber == productNumberArray[t]).Result;
                            storeStockContent.StorePutContentId = storePutContent.Id;
                            storeStockContent.BinLocationId = query[i].BinLocationId;
                            storeStockContent.BinLocation = query[i].BinLocation;
                            storeStockContent.QualifiedNumber = query[i].QualifiedNumber;
                            storeStockContent.ProductCode = storePutContent.ProductCode;
                            storeStockContent.ProductCodeId = storePutContent.ProductCodeId;
                            storeStockContent.SendTime = storePutContent.SendTime;
                            storeStockContent.SendTimeId = storePutContent.SendTimeId;
                            //storeStockContent.ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description));
                            //storeStockContent.ProductCodeId = query[i].ProductCode;
                            //storeStockContent.SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description));
                            //storeStockContent.SendTimeId = query[i].SendTime;
                            storeStockContent.SendTimeLength = storePutContent.SendTime.Split(',').Count();
                            storeStockContent.ProductDrawingNo = productDrawingNo;
                            storeStockContent.ProductDrawingNoTwo = query[i].ProductDrawingNo;
                            storeStockContent.Years = year;
                            storeStockContent.ProductDrawingNo = query[i].ProductDrawingNo;
                            storeStockContent.ExpirationDate = expirationDate;
                            await _storeStockContentRepository.UpdateAsync(storeStockContent);
                        }
                    }
                    else
                    {
                        var storeStockContentList = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == input.ReleaseOrderDto.Id).AsNoTracking().ToList();
                        for (int p = 0 + i; p < storeStockContentList.Count(); p++)
                        {
                            var storeStockContent = _storeStockContentRepository.FirstOrDefaultAsync(s => s.Id == storeStockContentList[p].Id).Result;
                            storeStockContent.StorePutContentId = storePutContent.Id;
                            storeStockContent.BinLocationId = storeStockContentList[p].BinLocationId;
                            storeStockContent.BinLocation = storeStockContentList[p].BinLocation;
                            storeStockContent.QualifiedNumber = query[i].QualifiedNumber;
                            storeStockContent.ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description));
                            storeStockContent.ProductCodeId = storeStockContentList[p].ProductCode;
                            storeStockContent.SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description));
                            storeStockContent.SendTimeId = storeStockContentList[p].SendTime;
                            storeStockContent.SendTimeLength = query[i].SendTime.Split(',').Count();
                            storeStockContent.ProductDrawingNo = storeStockContentList[p].ProductDrawingNo;
                            storeStockContent.ExpirationDate = expirationDate;
                            await _storeStockContentRepository.UpdateAsync(storeStockContent);
                        }
                    }
                    #endregion

                    #region 更新合格证记录表
                    var storePutRecord = _storePutRecordRepository.FirstOrDefaultAsync(s => s.ReleaseOrder == input.ReleaseOrderDto.ReleaseOrder).Result;
                    storePutRecord.QualifiedNumber = query[i].QualifiedNumber;
                    await _storePutRecordRepository.UpdateAsync(storePutRecord);
                    #endregion
                }
                result.code = 0;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 库信息修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> UpdateStoreInfo(StoreInfoDto input)
        {
            ResultMessage result = new ResultMessage();
            try
            {
                #region 权限控制,只有仓库人员能确认入库
                var userId = GetCurrentUser().Id; //add 11/30
                //var userId = 2;
                var userOrganizationUnit = _userOrganizationUnitRepository.GetAll();
                var organizationUnitList = from ou in _organizationUnitRepository.GetAll().Where(s => s.DisplayName == "仓库人员")
                                           join uou in userOrganizationUnit
                                           on ou.Id equals uou.OrganizationUnitId
                                           where uou.UserId == userId
                                           select ou;
                if (organizationUnitList == null)
                {
                    result.code = 1;
                    result.Message = "只有仓库人员能修改库存信息";
                    return result;
                }
                #endregion
                #region 必填项去除前后空格并判断null值
                if (input.WarehousMethod == 1)
                {
                    input.ReleaseOrder = input.ReleaseOrder.Trim();
                    if (input.ReleaseOrder == null)
                    {
                        result.code = 1;
                        result.Message = "放行单号不能填空格";
                        return result;
                    }
                    //放行单号重复校验
                    var releaseOrder = _storePutContentRepository.FirstOrDefaultAsync(s => s.ReleaseOrder == input.ReleaseOrder && s.Id != input.Id).Result;
                    if (releaseOrder != null)
                    {
                        result.code = 1;
                        result.Message = "放行单号不能重复";
                        return result;
                    }
                }
                if (input.WarehousMethod == 2 || input.WarehousMethod == 0)
                {
                    input.QualifiedNumber = input.QualifiedNumber.Trim();
                    if (input.QualifiedNumber == null)
                    {
                        result.code = 1;
                        result.Message = "合格证号不能填空格";
                        return result;
                    }
                }
                input.ProductDrawingNo = input.ProductDrawingNo.Trim();
                if (input.ProductDrawingNo == null)
                {
                    result.code = 1;
                    result.Message = "产品图号不能填空格";
                    return result;
                }
                input.ProductDrawingNo = input.ProductDrawingNo.ToUpper();
                input.ProductName = input.ProductName.Trim();
                if (input.ProductName == null)
                {
                    result.code = 1;
                    result.Message = "产品名称不能填空格";
                    return result;
                }
                input.Batch = input.Batch.Trim();
                if (input.Batch == null)
                {
                    result.code = 1;
                    result.Message = "批次不能填空格";
                    return result;
                }
                input.Module = input.Module.Trim();
                if (input.Module == null)
                {
                    result.code = 1;
                    result.Message = "规格不能填空格";
                    return result;
                }
                input.Module = input.Module.Replace("X", "x").Replace("*", "x").Replace("×", "x").ToUpper();
                #endregion
                if (input.StoreQuality != input.StoreStockContentDto.Count() || input.StoreQuality == 0)
                {
                    result.code = 1;
                    result.Message = "合格证上的数量和产品编号(件号)数量不符且数量不能为0";
                    return result;
                }
                List<string> productNumberList = new List<string>();
                List<string> productNumberShowList = new List<string>();
                var count = 0;
                if (input.ProductNumber != null)
                {
                    string[] productNumber = input.ProductNumber.Split(",").ToList().Where(d => !string.IsNullOrEmpty(d) && d != "undefined" && d != "").ToArray();
                    count = input.ProductNumber.Split(",").Length;
                    productNumberShowList = new List<string>(productNumber);

                    productNumberList = new List<string>(productNumber);
                    for (int i = 0; i < input.StoreQuality - productNumber.Length; i++)
                    {
                        productNumberList.Add("undefined");
                    }
                }
                else
                {
                    for (int i = 0; i < input.StoreQuality; i++)
                    {
                        productNumberList.Add("undefined");
                    }
                }
                if (input.StoreQuality == 0 || input.StoreQuality < count)
                {
                    result.code = 1;
                    result.Message = "合格证上的数量不能为0或者比产品编号的个数少";
                    return result;
                }
                var storePutContenRole = _storePutContentRepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                var oldProductNumeber = storePutContenRole.ProductNumberShow;
                var nodeCategory = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == input.MaterialCategory && s.LevelNum == 2);
                var node = _materialsNodeRepository.FirstOrDefault(s => s.MaterialTypeName == input.MaterialsNode && s.LevelNum == 1);
                List<string> sendTime = new List<string>(input.SendTime.Split(',').ToArray());
                List<string> productCode = new List<string>(input.ProductCode.Split(',').ToArray());
                #region 根据图号、规格 判断物料详细表中是否存在 更新物料信息
                var queryStoreContent = _storePutContentRepository.FirstOrDefault(t => t.QualifiedNumber == input.QualifiedNumber);
                var productDrawingNo = input.ProductDrawingNo;
                var materialType = _materialsNodeRepository.FirstOrDefault(d => d.Id == input.MaterialsNodeId);
                if (productDrawingNo.IndexOf("-") >= 0 && materialType.MaterialTypeName == "标准件")
                {
                    productDrawingNo = input.ProductDrawingNo.Substring(0, input.ProductDrawingNo.LastIndexOf("-"));
                }
                var queryMaterialsContents = _materialsContentRepository.FirstOrDefault(t => t.MaterialNo == productDrawingNo && t.Model == input.Module);
                if (queryMaterialsContents.IsUsed == 0)
                {
                    result.code = 1;
                    result.Message = "该物料已经停用";
                    return result;
                }
                //var queryMaterialsContents = _materialsContentRepository.FirstOrDefaultAsync(t => t.MaterialNo == input.ProductDrawingNo && t.Model == input.Module && t.Batch == input.Batch).Result;
                //如果存在，那就修改 如果添加成功后，一般不会有不存在的情况
                StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
                if (queryMaterialsContents == null)
                {
                    var materialsNode = _materialsNodeRepository.GetAll();
                    //var materialsContent = _materialsContentRepository.GetAll();

                    MaterialsEditContentDto materialsEditContentDto = new MaterialsEditContentDto();
                    {
                        //物料代码
                        materialsEditContentDto.MaterialNo = input.ProductDrawingNo;
                        //物料名称
                        materialsEditContentDto.MaterialName = input.ProductName;
                        //规格型号
                        materialsEditContentDto.Model = input.Module;
                        //类型id
                        materialsEditContentDto.MaterialsNodeId = node.Id;
                        //单位
                        materialsEditContentDto.UnitId = input.UnitId;
                        //是否使用 1：使用
                        materialsEditContentDto.IsUsed = 1;
                        //是否关键件 1：是
                        materialsEditContentDto.IsKeyPart = 1;
                        //是否标准件 1：是
                        materialsEditContentDto.IsStandard = 1;
                        //备注
                        materialsEditContentDto.Remark = input.Remark;
                        ////图号
                        //materialsEditContentDto.DrawingNo = input.ProductDrawingNo;
                        ////发次
                        //materialsEditContentDto.SendTime = materialsEditContentDto.SendTime;
                        //物料类别组合编码
                        materialsEditContentDto.MaterialTypeCode = nodeCategory.MaterialsTypeCode;
                        //物料属性 字段待讨论
                        materialsEditContentDto.MaterialProperty = 3;
                        //物料细分类别
                        materialsEditContentDto.MaterialCategoryId = nodeCategory.Id;
                        //批次
                        materialsEditContentDto.Batch = input.Batch;
                    }
                    storeReturnIdDto = await _materialsAppServiceRepository.CreateOrUpdateMaterialsContent(materialsEditContentDto);
                }

                if (queryMaterialsContents != null)
                {
                    var nodeName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialsNodeId).MaterialTypeName;
                    var categoryName = _materialsNodeRepository.FirstOrDefault(s => s.Id == queryMaterialsContents.MaterialCategoryId).MaterialTypeName;
                    if (nodeName != input.MaterialsNode && categoryName != input.MaterialCategory)
                    {
                        result.code = 0;
                        result.Message = "物料分类、细类与物料详细信息不符";
                        return result;
                    }
                }
                #endregion

                #region 合格证信息修改
                var expirationDate = input.ExpirationDate ?? "2099-01-01T00:00:00.000Z";
                #region  仓库信息

                //仓库Id
                storePutContenRole.StoreId = input.StoreId;
                //仓库名称
                storePutContenRole.StroeName = input.StroeName;
                //储位ID
                storePutContenRole.BinLocationId = input.BinLocationId;
                //储位
                storePutContenRole.BinLocation = input.BinLocation;
                //物料细料ID
                if (storeReturnIdDto.MaterialsContentId != null)
                {
                    storePutContenRole.MaterialsContentId = (Guid)storeReturnIdDto.MaterialsContentId;
                }
                else
                {
                    storePutContenRole.MaterialsContentId = queryMaterialsContents.Id;
                }
                //放行单号
                storePutContenRole.ReleaseOrder = input.ReleaseOrder;
                //备注
                storePutContenRole.Remark = input.Remark;
                #endregion

                #region 合格证信息 
                //合格证号
                storePutContenRole.QualifiedNumber = input.QualifiedNumber;
                //产品图号
                storePutContenRole.ProductDrawingNo = input.ProductDrawingNo;
                //产品名称
                storePutContenRole.ProductName = input.ProductName;
                //批次
                storePutContenRole.Batch = input.Batch;
                //合格证号任务
                storePutContenRole.QualifiedTaskNumber = input.QualifiedTaskNumber;
                //数量
                storePutContenRole.Quantity = input.StoreQuality;
                //产品编号(件号)
                storePutContenRole.ProductNumber = string.Join(",", productNumberList.ToArray());
                storePutContenRole.ProductNumberShow = string.Join(",", productNumberShowList.ToArray());
                //特殊记载
                storePutContenRole.SpecialRecords = input.SpecialRecords;
                if (input.WarehousMethod == 2 && input.NonMetallicPressingDate == null)
                {

                    storePutContenRole.MaterialBrandStatus = input.MaterialGrade + "/" + input.MaterialStatus + "/" + input.MaterialSpecification;
                    storePutContenRole.NonmetallicMaterialsBrand = null;
                }
                if (input.WarehousMethod == 2 && input.NonMetallicPressingDate != null)
                {
                    storePutContenRole.MaterialBrandStatus = null;
                    storePutContenRole.NonmetallicMaterialsBrand = input.MaterialGrade + "/" + input.MaterialStatus + "/" + input.MaterialSpecification;
                }
                //炉(批)号
                storePutContenRole.HeatNumber = input.HeatNumber;
                //化(试)验号
                storePutContenRole.Mthd = input.Mthd;
                //批次号
                storePutContenRole.BatchNo = input.BatchNo;
                //压制日期
                storePutContenRole.SuppressionDate = input.SuppressionDate;
                //处理技术问题文件编号
                storePutContenRole.DocumentNo = input.DocumentNo;
                //制造车间
                storePutContenRole.ManufacturingWorkshop = input.ManufacturingWorkshop;
                //生产工人
                storePutContenRole.ProductionWorkers = input.ProductionWorkers;
                //工(组)长
                storePutContenRole.Foreman = input.Foreman;
                //检验员
                storePutContenRole.Inspector = input.Inspector;
                //日期
                storePutContenRole.Date = input.Date;
                //质控卡号
                storePutContenRole.QCCardNo = input.QCCardNo;
                //装配任务号
                storePutContenRole.AssemblyTaskNumber = input.AssemblyTaskNumber;
                //阶段标记
                storePutContenRole.StageMark = input.StageMark;
                //材料牌号
                storePutContenRole.MaterialGrade = input.MaterialGrade;
                //材料状态
                storePutContenRole.MaterialStatus = input.MaterialStatus;
                ////材料规格
                //storePutContenRole.MaterialSpecification = input.MaterialSpecification;
                ////标准件规格
                //storePutContenRole.StandardSpecification = input.StandardSpecification;
                //技术条件
                storePutContenRole.TechnicalConditions = input.TechnicalConditions;
                //材料合格证
                storePutContenRole.MaterialCertificate = input.MaterialCertificate;
                //供应单位
                storePutContenRole.CooperationCertificate = input.CooperationCertificate;
                //SupplyCompany
                storePutContenRole.SupplyCompany = input.SupplyCompany;
                //非金属制造日期
                storePutContenRole.NonMetallicManufacturingDate = input.NonMetallicManufacturingDate;
                //非金属压制日期
                storePutContenRole.NonMetallicPressingDate = input.NonMetallicPressingDate;
                #endregion

                #region 基础信息  
                //型号(产品代号)
                storePutContenRole.ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description));
                storePutContenRole.ProductCodeId = input.ProductCode;
                //发次
                var index = storePutContenRole.ProductCode.IndexOf("系列");
                if (index > 0)
                {
                    storePutContenRole.SendTime = "全发次";
                    var st = _sysCodeRepository.FirstOrDefault(s => s.Description == "全发次");
                    if (st != null)
                    {
                        storePutContenRole.SendTimeId = st.Id.ToString().ToUpper();
                    }
                }
                else
                {
                    storePutContenRole.SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description));
                    storePutContenRole.SendTimeId = input.SendTime;
                }
                //规格型号
                storePutContenRole.Module = input.Module;
                //有效期止
                storePutContenRole.ExpirationDate = expirationDate;
                //单位Id
                storePutContenRole.UnitId = input.UnitId;
                //单位
                storePutContenRole.Unit = input.Unit;
                //转批次
                storePutContenRole.TurnBatch = input.TurnBatch;
                //物料属性
                storePutContenRole.MaterialsProperty = (MaterialsPropertys)input.MaterialsProperty;
                //入库方式
                storePutContenRole.WarehousMethod = (StorePutContent.WarehousMethods)input.WarehousMethod;
                _iOperationHistoryAppService.InsertOperationLogNew(storePutContenRole.Id, BusinessTypes.仓库管理, OperationTypes.仓库修改物料, "修改仓库物料信息");
                //_iOperationHistoryAppService.InsertOperationLog(storePutContenRole.Id, 6, 20, "修改仓库物料信息");
                #endregion
                await _storePutContentRepository.UpdateAsync(storePutContenRole);
                #endregion

                #region 库存信息修改
                var materialsContent = _storeStockRepository.FirstOrDefault(s => s.MaterialsContentId == input.MaterialsContentId && s.StoreId == input.StoreId);
                var storeStockId = Guid.Empty;
                if (materialsContent == null)
                {
                    result.code = 0;
                    result.Message = "修改后的物料与入库时的物料不一致";
                    return result;
                }
                if (materialsContent != null)
                {
                    if (!string.IsNullOrEmpty(oldProductNumeber))
                    {
                        if (!string.IsNullOrEmpty(materialsContent.ProductNumber))
                        {
                            // 产品编号(件号)
                            materialsContent.ProductNumber = string.Join(",", ((materialsContent.ProductNumber.Split(",")).Except(oldProductNumeber.Split(","))));
                        }
                        if (!string.IsNullOrEmpty(materialsContent.StoreProductNumber))
                        {
                            // 库存产品编号(件号)
                            materialsContent.StoreProductNumber = string.Join(",", ((materialsContent.StoreProductNumber.Split(",")).Except(oldProductNumeber.Split(","))));
                        }
                    }
                    if (!string.IsNullOrEmpty(storePutContenRole.ProductNumberShow))
                    {
                        // 产品编号(件号)
                        materialsContent.ProductNumber = materialsContent.ProductNumber + "," + storePutContenRole.ProductNumberShow;
                        // 库存产品编号(件号)
                        materialsContent.StoreProductNumber = materialsContent.StoreProductNumber + "," + storePutContenRole.ProductNumberShow;

                    }
                    storeStockId = _storeStockRepository.InsertOrUpdateAndGetId(materialsContent);
                }
                #endregion

                #region 库存详细信息修改
                string[] productNumberArray = input.ProductNumber.Split(",");
                for (var i = 0; i < input.StoreStockContentDto.Count(); i++)
                {
                    var storeStockContent = _storeStockContentRepository.FirstOrDefaultAsync(s => s.Id == input.StoreStockContentDto[i].Id).Result;

                    //物料细料ID
                    if (storeReturnIdDto.MaterialsContentId != null)
                    {
                        storeStockContent.MaterialsContentId = (Guid)storeReturnIdDto.MaterialsContentId;
                    }
                    else
                    {
                        storeStockContent.MaterialsContentId = queryMaterialsContents.Id;
                    }
                    //储位ID
                    storeStockContent.BinLocationId = input.BinLocationId;
                    // 储位
                    storeStockContent.BinLocation = input.BinLocation;
                    // 产品名称
                    storeStockContent.ProductName = input.ProductName;
                    // 型号(产品代号)
                    storeStockContent.ProductCode = storePutContenRole.ProductCode;
                    storeStockContent.ProductCodeId = storePutContenRole.ProductCodeId;
                    //storeStockContent.ProductCode = string.Join(",", _sysCodeRepository.GetAll().Where(s => productCode.Contains(s.Id.ToString())).Select(s => s.Description));
                    //storeStockContent.ProductCodeId = input.ProductCode;
                    // 发次
                    storeStockContent.SendTime = storePutContenRole.SendTime;
                    storeStockContent.SendTimeId = storePutContenRole.SendTimeId;
                    //storeStockContent.SendTime = string.Join(",", _sysCodeRepository.GetAll().Where(s => sendTime.Contains(s.Id.ToString())).Select(s => s.Description));
                    //storeStockContent.SendTimeId = input.SendTime;
                    storeStockContent.SendTimeLength = storePutContenRole.SendTime.Split(',').Count();
                    //有效期止
                    storeStockContent.ExpirationDate = expirationDate;
                    string productNumber = null;
                    if (productNumberArray[i] != "undefined" && productNumberArray[i] != "" && productNumberArray[i] != null) productNumber = productNumberArray[i].ToString();
                    storeStockContent.ProductNumber = productNumber;
                    await _storeStockContentRepository.UpdateAsync(storeStockContent);
                }
                #endregion
                result.code = 0;
                return result;
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 查询放行单号详细资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ReleaseOrderDto> GetReleaseOrderContentList(Guid id)
        {
            var releaseOrder = _storePutContentRepository.FirstOrDefault(s => s.Id == id);
            var materialsContents = _materialsContentRepository.FirstOrDefault(s => s.Id == releaseOrder.MaterialsContentId);
            ReleaseOrderDto releaseOrderDto = new ReleaseOrderDto()
            {
                Id = releaseOrder.Id,
                StorePutNo = releaseOrder.StorePutNo,
                BinLocationId = releaseOrder.BinLocationId,
                BinLocation = releaseOrder.BinLocation,
                StoreId = releaseOrder.StoreId,
                StroeName = releaseOrder.StroeName,
                ReleaseOrder = releaseOrder.ReleaseOrder,
                StorePutTime = releaseOrder.StorePutTime,
                StorePutPeopleId = releaseOrder.CreatorUserId,
                // 确认人ID
                IdentifyingPeopleId = releaseOrder.IdentifyingPeopleId,

                IdentifyingTime = releaseOrder.IdentifyingTime,
                //MaterialsContentId = releaseOrder.MaterialsContentId,
                //产品图号
                ProductDrawingNo = releaseOrder.ProductDrawingNo,
                //产品名称
                ProductName = releaseOrder.ProductName,
                //批次
                Batch = releaseOrder.Batch,
                //合格证号任务
                QualifiedTaskNumber = releaseOrder.QualifiedTaskNumber,
                //数量
                Quantity = releaseOrder.Quantity,
                //产品编号(件号)
                ProductNumber = releaseOrder.ProductNumber,
                //特殊记载
                SpecialRecords = releaseOrder.SpecialRecords,
                //型号(产品代号)
                ProductCode = releaseOrder.ProductCode,
                //发次
                SendTime = releaseOrder.SendTime,
                //物料细分类别
                MaterialCategory = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContents.MaterialCategoryId).MaterialTypeName,
                MaterialCategoryId = materialsContents.MaterialCategoryId,
                //物料类别
                MaterialsNode = _materialsNodeRepository.FirstOrDefault(s => s.Id == materialsContents.MaterialsNodeId).MaterialTypeName,
                MaterialsNodeId = materialsContents.MaterialsNodeId,
                //规格型号
                Module = releaseOrder.Module,
                //有效期止
                ExpirationDate = releaseOrder.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : releaseOrder.ExpirationDate,
                //单位Id
                UnitId = releaseOrder.UnitId,
                //单位
                Unit = releaseOrder.Unit,
            };
            return releaseOrderDto;
        }
        /// <summary>
        ///放行单号查询
        /// </summary>
        /// <param name="productDrawingNo"></param>
        /// <param name="module"></param>
        /// <param name="batch"></param>
        /// <returns></returns>
        public List<MaterialsOtherDto> GetReleaseOrder()
        {
            var releaseOrderList = from spc in _storePutContentRepository.GetAll().Where(t => t.QualifiedNumber == null && t.ReleaseOrder != null && t.StoreStateContent == StoreState.已入库)
                                   select new MaterialsOtherDto
                                   {
                                       label = spc.ReleaseOrder,
                                       value = spc.Id
                                   };
            if (releaseOrderList.Count() > 0)
            {
                return releaseOrderList.ToList();
            }
            return new List<MaterialsOtherDto>();
        }
        /// <summary>
        /// 产品隔离
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> QuarantineProduct(QuarantineProductDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                #region 权限控制,只有仓库人员能确认入库
                var userId = GetCurrentUser().Id; //add 11/30
                var userTemp = _userRepository.GetAll().ToList();
                var userOrganizationUnit = _userOrganizationUnitRepository.GetAll();
                var organizationUnitList = from ou in _organizationUnitRepository.GetAll().Where(s => s.DisplayName == "仓库人员")
                                           join uou in userOrganizationUnit
                                           on ou.Id equals uou.OrganizationUnitId
                                           where uou.UserId == userId
                                           select ou;
                if (organizationUnitList == null)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "只有仓库人员能修改库存信息";
                    return resultMessage;
                }
                #endregion
                var storePutContenRole = _storePutContentRepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                storePutContenRole.IsolationCode = input.IsolationCode;
                storePutContenRole.IsolationReason = input.IsolationReason;
                storePutContenRole.IsolationUserId = userId;
                storePutContenRole.IsolationUser = userTemp.FirstOrDefault(d => d.Id == userId).Surname + userTemp.FirstOrDefault(d => d.Id == userId).Name;
                storePutContenRole.IsolationTime = DateTime.Now;
                storePutContenRole.MaterialsProperty = MaterialsPropertys.隔离品;
                _iOperationHistoryAppService.InsertOperationLogNew(storePutContenRole.Id, BusinessTypes.仓库管理, OperationTypes.隔离物料, storePutContenRole.ProductName + "隔离物料");
                //_iOperationHistoryAppService.InsertOperationLog(storePutContenRole.Id, 6, 37, storePutContenRole.ProductName + "隔离物料");
                await _storePutContentRepository.UpdateAsync(storePutContenRole);
                var storeStock = _storeStockRepository.FirstOrDefault(s => s.MaterialsContentId == storePutContenRole.MaterialsContentId && s.StoreId == storePutContenRole.StoreId);
                //storeStock.StoreQuantity = storeStock.StoreQuantity - storePutContenRole.Quantity;
                //storeStock.FreeQuantityStock = storeStock.FreeQuantityStock - storePutContenRole.Quantity;
                //storeStock.UsableQuantityStock = storeStock.UsableQuantityStock - storePutContenRole.Quantity;
                //storeStock.UsableMatingQuantityStock = storeStock.UsableMatingQuantityStock - storePutContenRole.Quantity;
                //if (!string.IsNullOrEmpty(storePutContenRole.ProductNumberShow))
                //{
                //    var productNumber = storePutContenRole.ProductNumberShow.Split(",");
                //    for (int i = 0; i < productNumber.Length; i++)
                //    {
                //        storeStock.ProductNumber = storeStock.ProductNumber.Replace(productNumber[i],"").Replace(",,",",").TrimEnd(',').TrimStart(','); 
                //        storeStock.StoreProductNumber = storeStock.StoreProductNumber.Replace(productNumber[i], "").Replace(",,", ",").TrimEnd(',').TrimStart(',');
                //        storeStock.AbilityProductNumber = storeStock.AbilityProductNumber.Replace( productNumber[i], "").Replace(",,", ",").TrimEnd(',').TrimStart(',');
                //        storeStock.PreSuitProductNumber = storeStock.PreSuitProductNumber.Replace(productNumber[i], "").Replace(",,", ",").TrimEnd(',').TrimStart(',');
                //    }
                //}
                for (var i = 0; i < input.StoreStockContentDto.Count(); i++)
                {
                   var storeStockContent = _storeStockContentRepository.FirstOrDefaultAsync(s => s.Id == input.StoreStockContentDto[i].Id).Result;
                    storeStockContent.MaterialsProperty = MaterialsPropertys.隔离品;
                    await _storeStockContentRepository.UpdateAsync(storeStockContent);
                }
                //解除配套/预配套关系 0：否 1：是(等齐配套接口)
                if (input.IsOrNot == QuarantineProductDto.IsOrNots.是)
                {
                    // ExteriorCancelPreSuite 取消预配套
                    //ExteriorRelieveMating 取消配套
                    var suitList = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == input.Id && s.IsSuit == StoreStockContent.IsSuits.是);
                    var suitLists = ObjectMapper.Map<List<StoreStockContent>>(suitList.ToList());
                    await _matingManagerAppServiceRepository.ExteriorRelieveMating(suitLists);
                    _unitOfWorkManager.Current.SaveChanges();
                    var preSuiteList = _storeStockContentRepository.GetAll().Where(s => s.StorePutContentId == input.Id && s.IsPreSuit == StoreStockContent.IsSuits.是);
                    var preSuiteLists = ObjectMapper.Map<List<StoreStockContent>>(preSuiteList.ToList());
                    await _bomAnalyseAppServiceRepository.ExteriorCancelPreSuite(preSuiteLists);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 配套去向查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<PreSuiteInfoDto> GetPreSuiteInfo(Guid id)
        {
            var query = (from ssc in _storeStockContentRepository.GetAll()
                         join spc in _storePutContentRepository.GetAll()
                         on ssc.StorePutContentId equals spc.Id
                         join lp in _loadPieceEntityRepository.GetAll()
                         on ssc.LoadDetailsId equals lp.Id
                         join ws in _workStepEntityRepository.GetAll()
                         on lp.WorkStepEntityId equals ws.Id
                         join p in _processesEntityRepository.GetAll()
                         on ws.ProcessesEntityId equals p.Id
                         join bn in _bopNodeRepository.GetAll()
                         on ws.TechniqueEntityId equals bn.TechniqueEntityId
                         join t in _techniqueEntityRepository.GetAll()
                         on ws.TechniqueEntityId equals t.Id
                         where ssc.IsSuit == StoreStockContent.IsSuits.是 && spc.Id == id
                         select new PreSuiteInfoDto
                         {
                             ProductDrawingNo = ssc.ProductDrawingNo,
                             ProductName = ssc.ProductName,
                             Module = ssc.Module,
                             QualifiedNumber = ssc.QualifiedNumber,
                             //ssc.ProductNumber,
                             DesignatedModule = ssc.DesignatedModule,
                             DesignatedSendTime = ssc.DesignatedSendTime,
                             DesignatedXJ = ssc.DesignatedXJ,
                             NodeName = bn.NodeName,
                             TechniqueNumber = t.TechniqueNumber,
                             WorkStepNumber = ws.WorkStepNumber,
                             ProcessesName = p.ProcessesName
                         }).Distinct();
            if (query.Count() > 0)
            {
                List<PreSuiteInfoDto> preSuiteInfoDtos = new List<PreSuiteInfoDto>();
                PreSuiteInfoDto preSuiteInfoDto = new PreSuiteInfoDto();
                foreach (var item in query)
                {
                    var tempData = (from ssc in _storeStockContentRepository.GetAll()
                                    join spc in _storePutContentRepository.GetAll()
                                    on ssc.StorePutContentId equals spc.Id
                                    join lp in _loadPieceEntityRepository.GetAll()
                                    on ssc.LoadDetailsId equals lp.Id
                                    join ws in _workStepEntityRepository.GetAll()
                                    on lp.WorkStepEntityId equals ws.Id
                                    join p in _processesEntityRepository.GetAll()
                                    on ws.ProcessesEntityId equals p.Id
                                    join bn in _bopNodeRepository.GetAll()
                                    on ws.TechniqueEntityId equals bn.TechniqueEntityId
                                    join t in _techniqueEntityRepository.GetAll()
                                    on ws.TechniqueEntityId equals t.Id
                                    where ssc.IsSuit == StoreStockContent.IsSuits.是 && spc.Id == id
                                    select new
                                    {
                                        ssc.ProductDrawingNo,
                                        ssc.ProductName,
                                        ssc.Module,
                                        ssc.QualifiedNumber,
                                        ssc.ProductNumber,
                                        ssc.DesignatedModule,
                                        ssc.DesignatedSendTime,
                                        ssc.DesignatedXJ,
                                        bn.NodeName,
                                        t.TechniqueNumber,
                                        ws.WorkStepNumber,
                                        p.ProcessesName
                                    }).Where(p => p.DesignatedModule == item.DesignatedModule &&
                                            p.DesignatedSendTime == item.DesignatedSendTime &&
                                            p.DesignatedXJ == item.DesignatedXJ &&
                                            p.NodeName == item.NodeName &&
                                            p.TechniqueNumber == item.TechniqueNumber &&
                                            p.WorkStepNumber == item.WorkStepNumber &&
                                            p.ProcessesName == item.ProcessesName
                                            ).ToList();
                    if (tempData.Count > 0)
                    {
                        preSuiteInfoDto.ProductDrawingNo = item.ProductDrawingNo;
                        preSuiteInfoDto.ProductName = item.ProductName;
                        preSuiteInfoDto.Module = item.Module;
                        preSuiteInfoDto.QualifiedNumber = item.QualifiedNumber;
                        preSuiteInfoDto.ProductNumber = string.Join(",", tempData.Select(d => d.ProductNumber));
                        preSuiteInfoDto.DesignatedModule = item.DesignatedModule;
                        preSuiteInfoDto.DesignatedSendTime = item.DesignatedSendTime;
                        preSuiteInfoDto.DesignatedXJ = item.DesignatedXJ;
                        preSuiteInfoDto.NodeName = item.NodeName;
                        preSuiteInfoDto.TechniqueNumber = item.TechniqueNumber;
                        preSuiteInfoDto.WorkStepNumber = item.WorkStepNumber;
                        preSuiteInfoDto.WorkStepNumberStr = "工步-" + item.WorkStepNumber;
                        preSuiteInfoDto.ProcessesName = item.ProcessesName;
                        preSuiteInfoDto.CompleteQuality = tempData.Count();
                        //item.ProductNumber = string.Join(",", tempData.Select(d => d.ProductNumber));
                    }
                    preSuiteInfoDtos.Add(preSuiteInfoDto);
                }
                return preSuiteInfoDtos;
            }
            else
            {
                throw new UserFriendlyException("没有配套数据");
            }
        }
    }
}
